package com.tl.flowable.controller;

import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/index")
public class IndexController {

    //
    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    ProcessEngine processEngine;

    @GetMapping(value = "/process")
    public void showProcessPic(HttpServletResponse resp,String processId) throws IOException {
        if(null == processId){
            return;
        }
        // 获取进程实例
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if(null == pi){ // 无实例直接返回
            return;
        }
        // 获取执行流程
        List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processId).list();

        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exec : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exec.getId());
            activityIds.addAll(ids);
        }

        // 生成流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        // 过程配置
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        // 简图自动生成
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        // 图像流
        InputStream in = diagramGenerator.generateDiagram(bpmnModel,"png",activityIds,flows,engconf.getActivityFontName(),
                engconf.getLabelFontName(),engconf.getAnnotationFontName(),engconf.getClassLoader(),1.0,false);
        // 输出流
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int len = 0;
        try{
            out = resp.getOutputStream();
            while ((len = in.read(buf)) != -1){
                out.write(buf,0,len);
            }
        }catch (Exception e){
            if(null != in){
                in.close();
            }
            if(null != out){
                out.close();
            }
        }

    }

}
